<template>
  <div class="topbar">
    <div class="topbarWrap wrap">
      <div class="left">欢迎来到叩丁狼积分商城</div>
      <ul class="right">
        <li @click="changeIsShowLoginModel(true)">
          <img class="userImg" :src="userInfo.headImg" alt="" />
          用户名：{{ userInfo.nickName }}
        </li>
        <li>我的积分：{{ userInfo.coin }}</li>
        <li>获取积分</li>
        <li>叩丁狼官网</li>
        <li class="loginBtn" @click="openLoginModel(true)" v-show="!isLogined">
          登录
        </li>
        <li class="cart-btn" v-show="isLogined">
          <img src="../assets/img/cart.png" alt="" />
          <span>购物车</span>
          <strong>{{ cartTotal }}</strong>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { weiXinLoginApi } from "@/request/api";
export default {
  data() {
    return {
      //购物车总数
      // cartTotal: 0,  // 多个组件都要用，所以放 vuex 里
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModel: "showModel/changeIsShowLoginModel",
      changeIsLogined: "loginStatus/changeIsLogined",
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncShowToast: "showToast/asyncShowToast",
      asyncUpdateUserInfo: "userInfo/asyncUpdateUserInfo",
    }),
    openLoginModel(val) {
      this.changeIsShowLoginModel(val);
    },
  },
  computed: {
    ...mapState({
      isLogined: (state) => state.loginStatus.isLogined,
      userInfo: (state) => state.userInfo.userInfo,
      cartTotal: (state) => state.userInfo.cartTotal,
    }),
  },
  created() {
    // 好运的话 能拿到
    // console.log(this.$route.query.code);
    // 路由要是 history 模式，不然，无刷新，created 不重新执行，可能一样拿不到 this.$route.query
    this.$router.onReady(async () => {
      // console.log("等路由加载完回调函数获得的：", this.$route.query);
      const code = this.$route.query.code;
      // console.log({ code });

      if (code) {
        const weiXinLoginRes = await weiXinLoginApi({ code });
        console.log({ weiXinLoginRes });
        if (weiXinLoginRes.code == 0) {
          // alert("微信扫码登录成功！");
          this.asyncShowToast({
            show: true,
            tType: "success",
            tMsg: "微信扫码登录成功！!",
          });
          // 登录按钮切换为购物车
          this.changeIsLogined(true);
          localStorage.setItem("x-auth-token", weiXinLoginRes["x-auth-token"]);
          this.$router.push(this.$route.path);

          // 请求更新用户信息
          this.asyncUpdateUserInfo();
        } else if (weiXinLoginRes.code == 400) {
          // alert("二维码失效，请重新扫码！");
          this.asyncShowToast({
            show: true,
            tType: "error",
            tMsg: "二维码失效，请重新扫码！!",
          });
          this.changeIsShowLoginModel(true);
        } else if (weiXinLoginRes.code == 407) {
          // alert("未绑定手机号，请再登陆");
          this.asyncShowToast({
            show: true,
            tType: "warning",
            tMsg: "未绑定手机号，请再登陆!",
          });
          this.changeIsShowLoginModel(true);
          localStorage.setItem("uuid", weiXinLoginRes.uuid);
          this.$router.push(this.$route.path);
        }
      }
      // 在地址栏没有 code 干扰的情况下
      // 监听路由切换，进行改变 Tapbar 组件的 key值，利用key值更新，重载组件。更新用户登录状态。更新法二：
      if (!code) {
        // this.changeIsLogined(!!localStorage.getItem("x-auth-token"));
        let token = localStorage.getItem("x-auth-token");
        this.changeIsLogined(!!token);
        if (token) this.asyncUpdateUserInfo();
        if (!token) this.initUserInfo();
      }
    });
  },
  // 监听路由切换，更新用户登录状态。更新法一：
  watch: {
    /* "$route.path": {
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);
        if (oldVal == "/") return;
        this.changeIsLogined(!!localStorage.getItem("x-auth-token"));
      },
    }, */
  },
};
</script>

<style lang="less" scoped>
.topbar {
  height: 40px;
  line-height: 40px;
  background: #242b39;
  min-width: 1200px;
  color: #fffefe;
  font-size: 14px;
  font-weight: 300;
  .topbarWrap {
    display: flex;
    justify-content: space-between;
    .right {
      // width: 500px;
      display: flex;
      justify-content: space-between;
      li {
        margin: 0 10px;
        .userImg {
          width: 26px;
          height: 26px;
          border-radius: 13px;
          vertical-align: middle;
          margin-bottom: 3px;
        }
        &.loginBtn {
          width: 124px;
          background: #0a328e;
          text-align: center;
        }
        &.cart-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
          text-align: center;
          img {
            width: 20px;
            height: 19px;
            vertical-align: middle;
          }
          span {
            margin: 0 8px;
          }
          strong {
            width: 22px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            border-radius: 50%;
            background-color: #fd604d;
          }
        }
      }
    }
  }
}
</style>